<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { useNoticeAPI } from "@/services/notice";
import IconSearch from "@/assets/icons/IconSearch.vue";
import { debounce } from "lodash-es";
import { ElMessage, ElMessageBox } from "element-plus";

interface Announcement {
  id: number;
  title: string;
  context: string;
  uploadTime: string;
}

const noticeAPI = useNoticeAPI();

const announcementData = ref<Announcement[]>([]);
const query = ref({
  name: "",
});
const size = ref("15");
const options = [
  { value: "15", label: "15" },
  { value: "20", label: "20" },
  { value: "30", label: "30" },
  { value: "40", label: "40" },
  { value: "50", label: "50" },
];

const currentPage = ref(1);
const total = ref(0);
const loading = ref(false);

// Dialog controls
const showDetailDialog = ref(false);
const showAddDialog = ref(false);
const currentDetailData = ref<Announcement | null>(null);
const formData = ref({
  id: 0,
  title: "",
  context: "",
});

// 计算分页后的表格数据
const paginatedTableData = computed(() => {
  return announcementData.value;
});

// 处理页码改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
  getData();
};

// 处理每页显示数量改变
const handleSizeChange = (val: string) => {
  size.value = val;
  currentPage.value = 1;
  getData();
};

const handleViewDetail = (row: Announcement) => {
  currentDetailData.value = { ...row };
  showDetailDialog.value = true;
};

const handleEdit = (row: Announcement) => {
  formData.value = { ...row };
  showAddDialog.value = true;
};

const handleAdd = () => {
  formData.value = {
    id: 0,
    title: "",
    context: "",
  };
  showAddDialog.value = true;
};

const handleDelete = async (row: Announcement) => {
  try {
    await ElMessageBox.confirm("确定要删除该公告吗?", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 注意：根据实际后端接口实现删除逻辑
    ElMessage.success("删除成功");
    getData();
  } catch (error) {
    console.error("删除失败:", error);
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const submitForm = async () => {
  try {
    if (formData.value.id) {
      // 注意：根据实际后端接口实现更新逻辑
      ElMessage.success("更新成功");
    } else {
      // 添加新公告
      await noticeAPI.uploadNotice(formData.value.title, formData.value.context);
      ElMessage.success("添加成功");
    }
    showAddDialog.value = false;
    getData();
  } catch (error) {
    console.error("操作失败:", error);
    ElMessage.error("操作失败");
  }
};

// 搜索方法
const handleSearch = debounce(() => {
  currentPage.value = 1;
  getData();
}, 500);

const formatDate = (dateString: string | null) => {
  if (!dateString) return "未设置";
  const date = new Date(dateString);
  return date.toLocaleDateString() + " " + date.toLocaleTimeString();
};

/** 初始化 **/
onMounted(() => {
  getData();
});

// 监听搜索条件变化
watch(
  () => query.value.name,
  () => {
    handleSearch();
  }
);

const getData = async () => {
  try {
    loading.value = true;
    const response = await noticeAPI.getNewNotice();

    if (response.code === 200) {
      announcementData.value = response.data;
      total.value = response.data.length;
    } else {
      ElMessage.error(response.msg || "获取公告数据失败");
    }
  } catch (error) {
    console.error("获取公告数据失败:", error);
    ElMessage.error("获取公告数据失败");
  } finally {
    loading.value = false;
  }
};
</script>

<template>
  <!-- 模板部分保持不变，与之前相同 -->
  <div class="flex h-full gap-6">
    <div
      class="flex-1 bg-white rounded-lg p-4 flex flex-col justify-between min-w-0"
    >
      <div class="flex items-center justify-between gap-8 mb-4 flex-wrap">
        <div class="flex gap-8 flex-wrap">
        </div>
        <el-button type="primary" @click="handleAdd">
          <span>添加公告</span>
        </el-button>
      </div>

      <el-table
        v-loading="loading"
        :data="paginatedTableData"
        style="width: 100%"
        height="85%"
        header-row-class-name="table-header"
        cell-class-name="table-cell"
      >
        <el-table-column prop="id" label="ID" align="center" width="80" />
        <el-table-column prop="title" label="公告标题" align="center" />
        <el-table-column prop="context" label="公告内容" align="center" />
        <el-table-column label="发布时间" align="center">
          <template #default="{ row }">
            {{ formatDate(row.uploadTime) }}
          </template>
        </el-table-column>
      </el-table>

      <div class="h-[36px] flex items-center justify-between mt-6">
        <div>
          <span class="text-[#8a8a8f] text-sm mr-2">每页结果</span>
          <el-select
            v-model="size"
            placeholder="Select"
            style="width: 70px"
            class="input-grey"
            @change="handleSizeChange"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>
        <el-pagination
          background
          class="justify-items-end"
          layout="prev, pager, next"
          :total="total"
          :page-size="parseInt(size)"
          :current-page="currentPage"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 添加/编辑对话框 -->
  <el-dialog
    v-model="showAddDialog"
    :title="formData.id ? '编辑公告' : '添加公告'"
    width="50%"
  >
    <el-form :model="formData" label-width="100px">
      <el-form-item label="公告标题" required>
        <el-input v-model="formData.title" placeholder="请输入公告标题" />
      </el-form-item>
      <el-form-item label="公告内容" required>
        <el-input
          v-model="formData.context"
          type="textarea"
          :rows="6"
          placeholder="请输入公告内容"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="showAddDialog = false">取消</el-button>
      <el-button type="primary" @click="submitForm">确定</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss">
.icon {
  fill: currentColor;
  width: 20px;
  margin-right: 6px;
}
.input-grey {
  .el-input__wrapper {
    background: #f9f9f9;
    padding-left: 8px;
  }
  .el-select__wrapper {
    background: #f9f9f9;
  }
}
.el-table__header-wrapper {
  border-radius: 6px;
}
.table-header {
  background: #b88b7a !important;
  color: white;
  height: 50px !important;
  font-size: 15px;
  .el-table__cell {
    background: transparent !important;
    font-weight: 500;
  }
}
</style>